import { createApp } from 'vue'
import axios from 'axios'
import { createRouter, createWebHistory } from 'vue-router'
import './style.css'
// 导入Font Awesome
import '@fortawesome/fontawesome-free/css/all.min.css'
import App from './App.vue'
import FileShareView from './components/FileShareView.vue'
import MainLayout from './components/MainLayout.vue'
import LoginForm from './components/LoginForm.vue'
import RegisterForm from './components/RegisterForm.vue'

// 输出当前环境
console.log('当前环境:', import.meta.env.MODE);

// 配置axios默认值以处理CORS和OPTIONS请求
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
axios.defaults.headers.common['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE';
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.withCredentials = false; // 避免跨域凭证问题

// 配置axios基础URL
axios.defaults.baseURL = 'http://43.136.89.242';
console.log('API基础URL:', axios.defaults.baseURL);

// 创建路由配置
const routes = [
  {
    path: '/',
    name: 'home',
    component: MainLayout,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'login',
    component: LoginForm
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterForm
  },
  {
    path: '/share',
    name: 'share',
    component: FileShareView,
    meta: { requiresAuth: false }
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 全局导航守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  
  if (to.meta.requiresAuth && !token) {
    // 需要认证但未登录，重定向到登录页
    next({ name: 'login' });
  } else if (to.name === 'login' && token) {
    // 已登录但访问登录页，重定向到主页
    next({ name: 'home' });
  } else {
    next();
  }
});

// 全局错误处理
window.addEventListener('unhandledrejection', (event) => {
  console.error('未处理的Promise拒绝:', event.reason);
});

window.addEventListener('error', (event) => {
  console.error('全局错误:', event.error);
});

// 配置axios拦截器
axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    console.log('请求拦截器获取token:', token ? '已获取' : '未获取');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    
    return config
  },
  error => {
    console.error('请求拦截器错误:', error);
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  response => {
    console.log('响应拦截器接收到数据:', response.config.url);
    return response
  },
  error => {
    console.error('响应拦截器错误:', error.message);
    
    // 忽略OPTIONS请求错误
    if (error.request && error.request.method === 'OPTIONS') {
      console.log('忽略OPTIONS请求错误');
      // 返回一个解决的Promise而不是拒绝的Promise
      return Promise.resolve({
        data: { code: -1, message: 'OPTIONS请求被忽略' }
      });
    }
    
    if (error.response && error.response.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      window.location.reload()
    }
    return Promise.reject(error)
  }
)

const app = createApp(App);

// 使用路由
app.use(router);

// 全局错误处理
app.config.errorHandler = (err, vm, info) => {
  console.error('Vue错误处理:', err, info);
};

app.mount('#app')
